package com.haoshuang.zhouzhoubang.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils

import com.alipay.sdk.app.PayTask
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.ActivityBond5Binding
import com.haoshuang.zhouzhoubang.model.bean.BjBean
import com.haoshuang.zhouzhoubang.ui.adapter.BondAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.BjDialog2
import com.haoshuang.zhouzhoubang.ui.page.help.detail.HelpDetailActivity
import com.haoshuang.zhouzhoubang.ui.vm.BondViewModel55
import com.haoshuang.zhouzhoubang.utils.Event
import com.haoshuang.zhouzhoubang.utils.PayResult
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils

import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 *
 */
class BondActivity55 : BaseVMActivity<BondViewModel55, ActivityBond5Binding>() {

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            appBar.tvTitle.text = "保证金补交"
        }
    }

    var list = arrayListOf<BjBean>()
    lateinit var adapter: BondAdapter
    var pay_type = 1

    var service_id=""
    override fun initData() {
        vm.getData()
        binding.apply {
            tvName.clickWithTrigger {
                if (list.size==0){
                    toast("没有可退款的项目")
                    return@clickWithTrigger
                }
                XPopup.Builder(this@BondActivity55)
                    .asCustom(BjDialog2(this@BondActivity55,list) {
                        tvName.text=it.cate_name
                        tvPrice.text="￥"+it.money
                        order_amount=it.money
                        service_id=it.service_id
                    })
                    .show()
            }
            tvBzj.clickWithTrigger {
                var url="${URLConstants.baseUrl}/index/index/agreement?id=9"
                startPage<HelpDetailActivity>("title" to "保证金规则","url" to url)
            }
            llWx.clickWithTrigger {
                ivWx.setImageResource(R.mipmap.dz_ok)
                ivZfb.setImageResource(R.mipmap.dz_wx)
                pay_type = 1
            }
            llZfb.clickWithTrigger {
                ivWx.setImageResource(R.mipmap.dz_wx)
                ivZfb.setImageResource(R.mipmap.dz_ok)
                pay_type = 2
            }
            tvNext.clickWithTrigger {


                if (pay_type == 1) {
                    vm.getData3(
                        "service_id" to service_id,
                        "pay_type" to pay_type,
                        "state" to 1,
                        "id" to team_id,
                        "type" to 2,
                        "order_amount" to order_amount
                    )
                } else {
                    vm.getData2(
                        "service_id" to service_id,
                        "pay_type" to pay_type,
                        "state" to 1,
                        "id" to team_id,
                        "type" to 2,
                        "order_amount" to order_amount
                    )
                }

            }
        }
    }

    private val SDK_PAY_FLAG = 1
    fun payAlipay(mContext: Context?, orderNo: String) {
        val payRunnable = Runnable {
            val alipay = PayTask(mContext as Activity?)
            val result = alipay.payV2(orderNo, true)
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    @SuppressLint("HandlerLeak")
    var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)


                    val resultInfo = payResult.result
                    val resultStatus = payResult.resultStatus

                    if (TextUtils.equals(resultStatus, "9000")) {
                        toast("支付成功")
                       // startPage<SuccessActivity>()
                        finish()
                    } else {
                       toast("支付失败")

                    }
                }

                else -> {}
            }
        }
    }

    var ids = 0
    var order_amount = ""
    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageEvent: Event) {

        if (messageEvent.code == 80112) {
            toast("支付成功")
            finish()
        }

    }
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    override fun startObserve() {
        vm.getData3.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                var   api = WXAPIFactory.createWXAPI(this@BondActivity55, Config.WX_ID, false)
                PreferenceUtils.putString("Wxpay","6")
                PaymentUtil.payWxPayment(api,it)
            }
        }
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                payAlipay(this@BondActivity55, it?.body!!)
            }
        }
        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                list.addAll(it!!)
            }
        }
    }

}